package com.zhxin.nettylab.decoder.chapter1;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;
import io.netty.handler.codec.http.HttpResponseDecoder;

import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * @ClassName StringReplayDecoder
 * @Description // 字符串解码器
 *              // 在实际的开发中，不太建议继承ReplayingDecoder这个类
 * @Author singleZhang
 * @Email 405780096@qq.com
 * @Date 2020/12/7 0007 下午 2:30
 **/
public class StringReplayDecoder extends ReplayingDecoder<StringReplayDecoder.Status> {

    enum Status {
        PARSE_1, PARSE_2
    }

    private int length;
    private byte[] inBytes;

    public StringReplayDecoder() {
        //构造函数中，需要初始化父类的state 属性，表示当前阶段
        super(Status.PARSE_1);
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws UnsupportedEncodingException {

        switch (state()){
            case PARSE_1:
                length = in.readInt(); //读取长度
                inBytes = new byte[length];
                checkpoint(Status.PARSE_2); //设置“读指针断点”为当前的读取位置,进入第二步解析内容
                break;
            case PARSE_2:
                in.readBytes(inBytes,0,length);
                out.add(new String(inBytes,"UTF-8"));
                checkpoint(Status.PARSE_1); //设置“读指针断点”为当前的读取位置,返回第一步 读取内容
                break;
            default:
                break;
        }

    }
}
